<?php
namespace App\Services\WeChat\Strategies;

use App\Wechat\MyAccessToken;
use EasyWeChat\Factory;
use App\Services\WeChat\MessageSenderInterface;

class OfficialAccountStrategy implements MessageSenderInterface
{
    protected $app;

    public function __construct()
    {
        $this->app = app('easywechat.official_account')
            ->setAccessToken(new MyAccessToken())
            ->getClient();
    }

    public function send(string $openid, array $data, string $templateId = null)
    {
        $options = [
            'touser' => $openid,
            'template_id' => $templateId,
            'data' => $data,
            // 添加小程序特有参数（如跳转页面）
            'url' => $data['page'],
            'client_msg_id'=>$data['client_msg_id']
        ];
        if($data['miniprogram']){
            $options['miniprogram'] = $data['miniprogram'];
        }
        $response = $this->app->post('/cgi-bin/message/template/send',['json'=>$options] );

        $wxResponse = json_decode($response->getContent(),true); // 这里会抛出异常
        if(isset($wxResponse) && $wxResponse['errcode']>0){
            throw new \Exception($wxResponse['errmsg'],$wxResponse['errcode']);
        }
    }
}
